﻿using AutoMapper;
using Benefactor.Models.DtoModels;
using Benefactor.Services;
using Benefactor.Services.Repositories;
using Bigway.Common.Models.DtoModels;
using Microsoft.AspNetCore.Mvc;

namespace Benefactor.Controllers;
using static Errors;

[ApiController]
[Route("api/referer_commission")]
public class RefererCommissionController(
    IRefererCommissionRepository refererCommissionRepository,
    IAppConfig appConfig,
    IMapper mapper,
    ILogger<RefererCommissionController> logger): ControllerBase
{
    [HttpGet]
    public async Task<GetRefererCommissionsResponseDto> GetRefererCommissions(
        [FromQuery(Name = "api_key")] string apiKey,
        [FromQuery] GetRefererCommissionsRequest request,
        CancellationToken token = default
    )
    {
        if (apiKey != appConfig.ApiKey)
            return Unauthorized<GetRefererCommissionsResponseDto>();

        logger.LogInformation("Getting referer commissions...");
        var (systemId, refererAccount) = (request.system_id, request.referer_account);
        var refererCommissions = await refererCommissionRepository
            .GetAllAsync(query =>
            {
                query = query.Where(x => !x.IsDeleted && x.SystemId == systemId);

                if (!string.IsNullOrEmpty(refererAccount))
                    query = query.Where(x => x.RefererAccount == refererAccount);

                query = query.Includes(x => x.RefererCommissionRecords)
                    .Includes(x => x.RefererCommissionWithdrawalRecords);

                query = query.OrderByDescending(x => x.CreateTime);

                return query;
            }, token);

        return new GetRefererCommissionsResponseDto
        {
            Data = refererCommissions
                .Select(mapper.Map<RefererCommissionInfo>)
        };
    }
}